package com.siteseat.crudeq.broker.transport;

import java.util.Arrays;
import java.util.Collection;

import com.siteseat.crudeq.broker.netty.RequestHandler;
import com.siteseat.common.exception.InternalException;
import com.siteseat.common.foundation.Component;

/**
 *
 */
public class RequestHandlerRepository extends Component {

  private RequestHandler[] handlers = new RequestHandler[10];

  public void setHandlers( Collection<RequestHandler> handlers ) {
    for( RequestHandler handler: handlers ) {
      register( handler );
    }
  }
  
  public void setEnabled( boolean b ) {
    for( RequestHandler h: handlers ) {
      if( h != null ) {
        h.setEnabled( b );
      }
    }
  }
  
  /**
   * @param version
   * @param handler
   */
  public void register( RequestHandler handler ) {
    short version = handler.getVersion();

    if( version < 0 ) {
      throw new InternalException( "Invalid version: " + version + ": it must be >= 0" );
    }
    if( version > this.handlers.length ) {
      this.handlers = Arrays.copyOf( this.handlers, ( version + 1 ) * 3 / 2 );
    }

    Component.ensureInited( handler );

    if( this.handlers[version] != null ) {
      throw new InternalException( "Duplicated version: " + version );
    }

    this.handlers[version] = handler;
  }

  /**
   * @param version
   * @return
   */
  public RequestHandler get( short version ) {
    if( version < 0 ) {
      throw new InternalException( "Invalid version: " + version + ": it must be >= 0" );
    }
    if( version >= this.handlers.length ) {
      throw new InternalException( "Invalid version: " + version + ": it must be <" + this.handlers.length );
    }
    RequestHandler r = this.handlers[version];
    if( r == null ) {
      throw new InternalException( "Invalid version: " + version + ": it is not supported" );
    }
    return r;
  }
  
  /**
   * {@inheritDoc}
   */
  @Override
  protected void doInit() throws Exception {
    // do nothing so far
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doDestroy() throws Exception {
    // do nothing so far
  }

}
